<?php
namespace app\home\controller;

use app\common\model\UserPlatoon as UserPlatoonModel;
use app\common\model\AppointmentRich as AppointmentRichModel;
use app\common\model\AppointmentUpstart as AppointmentUpstartModel;

use app\common\component\user\UserModel;

use app\common\component\user_platoon\UserPlatoonService;
use app\common\component\user_platoon_log\UserPlatoonLogService;
use app\common\component\appointment_rich\AppointmentRichService;

class AppointmentRich extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

	public function index() {
		/*
		$selectAppointmentRich = AppointmentRichModel::where('status = 0 AND create_time < ' . (time() - (48 * 60 * 60))) -> select();
		foreach($selectAppointmentRich as $appointmentRich) {
			$appointmentRich -> status = 1;
			$appointmentRich -> save();
		}
		*/

		$this -> view -> assign('appointmentRichs', AppointmentRichModel::where('user_id', \think\Session::get('user_id')) -> order('help_appointment_rich_id DESC') -> paginate(10, true));

		return $this -> view -> fetch();
	}

	public function create() {
		$post = $this -> request -> post();

		if($this -> validate($post, ['appointment_price' => 'require|token']) !== true) {
			echo '<meta charset="utf-8"><script>alert("请勿重复提交!");window.history.go(-1);</script>';exit;
		}
		unset($post['__token__']);

		if(($post['appointment_price'] % 100) != 0) {
			echo '<meta charset="utf-8"><script>alert("请输入100的倍数!");window.history.go(-1);</script>';exit;
		}

		$post['user_id'] = \think\Session::get('user_id');

		$findLastHelpAppointmentRich = AppointmentRichModel::where('user_id', $post['user_id']) -> order('help_appointment_rich_id DESC') -> find();
		if(isset($findLastHelpAppointmentRich) && $post['appointment_price'] < $findLastHelpAppointmentRich -> appointment_price) {
    		echo '<meta charset="utf-8"><script>alert("您预约的' . $post['appointment_price'] . '金额不能小于您最后一次预约的金额!");window.history.go(-1);</script>';exit;
		}

		$getTeamNumber = \think\Cache::get('getTeamNumber_' . $post['user_id']);
		if(!$getTeamNumber) {
			$getTeamNumber = $this -> getTeamNumber($post['user_id']);
			if($getTeamNumber >= 20) {
				\think\Cache::set('getTeamNumber_' . $post['user_id'], $getTeamNumber);
			}
		}

		if($getTeamNumber >= 1) {
			if($getTeamNumber <= 5) {
				if($post['appointment_price'] > 500) {
					echo '<meta charset="utf-8"><script>alert("您预约的最高预约金额为500!");window.history.go(-1);</script>';exit;
				}
			} else if($post['appointment_price'] > ($getTeamNumber * 100)) {
				if($post['appointment_price'] > 2000) {
					echo '<meta charset="utf-8"><script>alert("您预约的最高预约金额为2000!");window.history.go(-1);</script>';exit;
				} else {
					echo '<meta charset="utf-8"><script>alert("您预约的最高预约金额为' . ($getTeamNumber * 100) . '!");window.history.go(-1);</script>';exit;
				}
			}
		} else {
			if($post['appointment_price'] > 100) {
	    		echo '<meta charset="utf-8"><script>alert("您预约的最高预约金额为100!");window.history.go(-1);</script>';exit;
			}
		}

		$currentTime = time();
		$APPOINTMENT_TIME = getParam('APPOINTMENT_TIME');
		$findHelpAppointmentRich = AppointmentRichModel::where('user_id', $post['user_id']) -> where('status', 0) -> where('create_time', '>', $currentTime - ($APPOINTMENT_TIME * 60 * 60)) -> find();
		if($findHelpAppointmentRich) {
			echo '<meta charset="utf-8"><script>alert("您的预约在' . $APPOINTMENT_TIME . '小时内，请耐心等候匹配!");window.history.go(-1);</script>';exit;
		}

		/*
		$findHelpAppointmentUpstart = AppointmentUpstartModel::where('user_id', $post['user_id']) -> where('status', 0) -> where('create_time', '>', $currentTime - ($APPOINTMENT_TIME * 60 * 60)) -> find();
		if($findHelpAppointmentUpstart) {
			echo '<meta charset="utf-8"><script>alert("您的预约在' . $APPOINTMENT_TIME . '小时内，请耐心等候匹配!");window.history.go(-1);</script>';exit;
		}
		*/

		$resultGetUserPlatoon = (new UserPlatoonService) -> getUserPlatoonId($post['user_id']);
		$platoon = round($post['appointment_price'] / getParam('PLATOON_GET_PRICE') / 100);
		if($resultGetUserPlatoon['data']['user_platoon'] -> price <= 0 || $resultGetUserPlatoon['data']['user_platoon'] -> price < $platoon) {
			echo '<meta charset="utf-8"><script>alert("您的排单币不足!");window.history.go(-1);</script>';exit;
		}

		\think\Db::startTrans();
		try {
			$resultHelpAppointmentRich = (new AppointmentRichService()) -> appointment($post);
			if($resultHelpAppointmentRich['code'] !== 0) {
    			throw new \Exception($resultHelpAppointmentRich['message']);
    		}

			$userName = \think\Session::get('user_name');
			$resultUserPlatoonLogService = (new UserPlatoonLogService()) -> log(2, 0, $platoon, $userName, $userName, '排单币使用', 1);
			if($resultUserPlatoonLogService['code'] != 0) {
				throw new \Exception($resultUserPlatoonLogService['message']);
			}

			if(!UserPlatoonModel::where('user_id', $post['user_id']) -> setDec('price', $platoon)) {
				throw new \Exception('预约失败');
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.history.go(-1);</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("' . $resultHelpAppointmentRich['message'] . '!");window.location.href="/appointment/rich";</script>';exit;
	}

	/**
	 * 求团队总人数
	 */
	public function getTeamNumber($promotion_ids) {
		$userIds = UserModel::where('promotion_id in(' . $promotion_ids . ')') -> column('user_id');
		if(empty($userIds)) {
			return 0;
		}

		$userIdsStr = '';
		foreach($userIds as $userId) {
			$userIdsStr .= $userId . ',';
		}
		$userIdsStr = substr($userIdsStr, 0, -1);

		return count($userIds) + $this -> getTeamNumber($userIdsStr);
	}
}
?>